<<<<<<< .mine
/**
 * 
 */
package br.srv.full.virtual.faces.manager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.richfaces.model.selection.Selection;

import br.srv.full.service.ServiceLocator;
import br.srv.full.virtual.engine.users.PersonsManager;
import br.srv.full.virtual.engine.users.PersonsManagerException;
import br.srv.full.virtual.entities.auth.Role;
import br.srv.full.virtual.entities.auth.User;
import br.srv.full.virtual.entities.persons.Worker;
import br.srv.full.virtual.entities.resume.UserLogin;
import br.srv.full.virtual.entities.resume.WorkerInClient;
import br.srv.full.virtual.faces.manager.menu.MenuManager;

/**
 * @author Delfino
 * 
 */
@TransactionManagement(TransactionManagementType.CONTAINER)
public final class UserRecordsManager {

	/**
	 * @author Delfino
	 * 
	 */
	public enum ActionLoginManager implements Action {
		/**
		 * 
		 */
		saveUserFailure,

		/**
		 * 
		 */
		saveUserSucess,

		/**
		 * 
		 */
		saveClientFailure
	}

	/**
	 * 
	 */
	private static final SelectItem SELECT_ITEM_NAO = new SelectItem(false, "Não");

	/**
	 * 
	 */
	private static final SelectItem SELECT_ITEM_SIM = new SelectItem(true, "Sim");

	private final Log log = LogFactory.getLog(getClass());

	/**
	 * 
	 */
	private LoginManager loginManager;

	private MenuManager menuManager;

	private PersonsManager personManager;

	/**
	 * 
	 */
	private User user;

	private Selection selectedWork;

	private WorkerInClient atualWork;

	private List<WorkerInClient> works;

	private Selection selectedClient;

	/**
	 * 
	 */
	private WorkSelectionManager workSelectionManager;

	/**
	 * @return the menuManager
	 */
	public MenuManager getMenuManager() {
		return menuManager;
	}

	/**
	 * @param p_menuManager
	 *            the menuManager to set
	 */
	public void setMenuManager(MenuManager p_menuManager) {
		menuManager = p_menuManager;
	}

	/**
	 * @return the loginManager
	 */
	public LoginManager getLoginManager() {
		return loginManager;
	}

	/**
	 * @param p_loginManager
	 *            the loginManager to set
	 */
	public void setLoginManager(LoginManager p_loginManager) {
		loginManager = p_loginManager;
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		if (user == null)
			updateUser();
		return user;
	}

	/**
	 * 
	 */
	private void updateUser() {
		try {
			UserLogin l_login = getLoginManager().getUserLogin();
			user = l_login.getUser();
			if (user == null) {
				l_login = getPersonManager().refreshUserLogin(l_login);
				getLoginManager().setUserLogin(l_login);
				getPersonManager().refresh(user, "works");
				user = l_login.getUser();

			}
		} catch (Exception e) {
			log.warn("Problemas ao Atualizar o User: " + user, e);
		}
	}

	/**
	 * @param p_user
	 *            the user to set
	 */
	public void setUser(User p_user) {
		user = p_user;
	}

	/**
	 * Salva os dados basicos do Usuário, e retorna qual página dever seguir.
	 * 
	 * @return
	 */
	public Action saveBaseUserRecord() {
		try {
			user = getPersonManager().update(user);
		} catch (PersonsManagerException e) {
			log.warn("Problemas ao salvar o usuário!", e);
			return ActionLoginManager.saveUserFailure;
		}
		getLoginManager().setUser(user);
		return ActionLoginManager.saveUserSucess;
	}

	/**
	 * Restora os dados Basicos do Usuário antes de ter salvo,
	 * 
	 * @return
	 */
	public String restoreBaseUserRecord() {
		return null;
	}

	/**
	 * Se o usuário é responsavel ou atua em alguma empresa, contem o numero de
	 * empresas.
	 * 
	 * @return
	 * 
	 * @see #getWorks()
	 */
	public Integer getNumClientsForUser() {
		Integer numClientsForUser = 0;
		try {
			List<WorkerInClient> l_works = getWorks();
			if (l_works != null)
				numClientsForUser = l_works.size();

		} catch (UserRecordsManagerException e) {
			log.warn("problemas ao obter o numero de clientes!", e);
		}
		log.info("Obtendo numero de Clientes: " + numClientsForUser);
		return numClientsForUser;
	}

	/**
	 * Retorna se atua em alguma empresa de alguma forma
	 * 
	 * é usado na página recordsmaintenance.xhtml.
	 * 
	 * @return
	 * @see #getNumClientsForUser()
	 */
	public Boolean isWorkerAtClients() {
		Boolean workerAtClients = getNumClientsForUser() > 0;
		log.info("Obtendo se trabalha em Clientes: " + workerAtClients);
		return workerAtClients;
	}

	public Boolean getWorkerAtClients() {
		return isWorkerAtClients();
	}

	/**
	 * Retorna as empresas onde o usuário logado atua!
	 * 
	 * @return
	 * @throws UserRecordsManagerException
	 */
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<WorkerInClient> getWorks() throws UserRecordsManagerException {
		try {
			User l_user = getUser();
			l_user = getPersonManager().refresh(l_user, User.FIELD_WORKS);

			if (l_user == null)
				throw new UserRecordsManagerException("Problemas ao obter o relacionamento do Usu'ario com o Cliente!");

			List<Worker> l_works = l_user.getWorks();
			if (works == null || l_works.size() != works.size() || !works.equals(l_works)) {
				List<WorkerInClient> l_result = new ArrayList<WorkerInClient>();

				setUser(l_user);
				l_works = l_user.getWorks();
				try {
					log.info("Atuando atualmente em: " + l_works.size());
					for (Worker l_work : l_works) {
						l_result.add(new WorkerInClient(l_work));
					}
				} catch (Exception e) {
					log.warn(" Problemas ao fazer um refresh do usuário!");
				}
				works = l_result;
			}
		} catch (PersonsManagerException e) {
			throw new UserRecordsManagerException(e);
		}
		return works;
	}

	public void setSelectedWork(Selection p_selection) {
		log.info(p_selection);
		selectedWork = p_selection;
	}

	/**
	 * @return the selectedWork
	 */
	public Selection getSelectedWork() {
		return selectedWork;
	}

	public void setSelectedClient(Selection p_selection) {
		log.info(p_selection);
		selectedClient = p_selection;
	}

	public void takeWorkSelected() {
		log.info("Take Client Selected!");
	}

	public WorkerInClient getAtualWork() {
		return atualWork;
	}

	public void setAtualWork(WorkerInClient p_client) {
		log.info(" Cadastrando o Trabalho Atual: " + p_client);
		atualWork = p_client;
	}

	public List<SelectItem> getSelectItensYesNo() {
		List<SelectItem> l_itens = new ArrayList<SelectItem>();

		l_itens.add(SELECT_ITEM_NAO);
		l_itens.add(SELECT_ITEM_SIM);

		return l_itens;
	}

	/**
	 * remove a empresa selecionada do usuário
	 */
	public String removeSelectedWorkForUser() {
		Selection l_selectedWork = getSelectedWork();
		Iterator l_works = l_selectedWork.getKeys();
		while (l_works.hasNext()) {
			Object l_obj = l_works.next();
			log.info(l_obj);

			// log.info("Removendo um trabalho " + l_selectedWork + " para o
			// usuário: " + getUser());
			Integer l_count = getNumClientsForUser();
			l_count = (l_count != null) ? --l_count : 0;

		}

		setAtualWork(null);

		return null;
	}

	/**
	 * Acionado quando se seleciona se o usu'ario atua ou n'ao em um cliente.
	 * 
	 * @param p_item
	 * @throws UserRecordsManagerException
	 */
	public void selectedWorkerAtClients(ValueChangeEvent p_item) throws UserRecordsManagerException {

		log.info("alterando e adicionando um novo Cliente se necessário!");
		Boolean l_workAtclients = getWorkerAtClients();
		if (!l_workAtclients)
			addMoreWorkForUser();

	}

	/**
	 * Remove a empresa selecionada do usuário.
	 * 
	 * @throws UserRecordsManagerException
	 * 
	 */
	public String addMoreWorkForUser() throws UserRecordsManagerException {
		log.info("Adicionando um novo cliente para o usuário: " + getUser());
		addWorkForUser(new WorkerInClient(getUser()));

		return null;
	}

	/**
	 * @param p_work
	 * @throws UserRecordsManagerException
	 */
	private void addWorkForUser(WorkerInClient p_work) throws UserRecordsManagerException {
		log.info("Adicionando um trabalho  " + p_work + " para o usuário: " + getUser());
		Integer l_count = getNumClientsForUser();
		l_count = (l_count != null) ? ++l_count : 1;

		getWorks().add(p_work);

		setAtualWork(p_work);

		takeWorkSelected();
	}

	public String cancelEditAtualWork() {
		return null;
	}

	@TransactionAttribute(TransactionAttributeType.MANDATORY)
	public Action saveEditAtualWork() {
		log.info("Salvando o Atual work");
		WorkerInClient l_atual = getAtualWork();

		try {
			getPersonManager().saveWork(l_atual);
		} catch (Exception e) {
			log.warn("Problemas ao salvar o atual trabalho para o usuário: " + l_atual.getUser(), e);
		}

		return null;
	}

	public List<SelectItem> getRoleTypesForUserWorkOnClient() {
		List<Role> l_roles = getPersonManager().getWorkerRoles();
		List<SelectItem> l_itens = new ArrayList<SelectItem>();
		for (Role l_workerRole : l_roles) {
			l_itens.add(new SelectItem(l_workerRole, l_workerRole.getName()));
		}
		return l_itens;
	}

	/**
	 * @return
	 */
	private PersonsManager getPersonManager() {
		if (personManager == null) {
			personManager = ServiceLocator.getService(PersonsManager.class);
		}

		return personManager;
	}

	/**
	 * @return the selectedClient
	 */
	public Selection getSelectedClient() {
		return selectedClient;
	}

	/**
	 * @return the workSelectionManager
	 */
	public WorkSelectionManager getWorkSelectionManager() {
		return workSelectionManager;
	}

	/**
	 * @param p_workSelectionManager
	 *            the workSelectionManager to set
	 */
	public void setWorkSelectionManager(WorkSelectionManager p_workSelectionManager) {
		workSelectionManager = p_workSelectionManager;
	}
}
=======
/**
 * 
 */
package br.srv.full.virtual.faces.manager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.richfaces.model.selection.Selection;

import br.srv.full.service.ServiceLocator;
import br.srv.full.virtual.engine.users.PersonsManager;
import br.srv.full.virtual.engine.users.PersonsManagerException;
import br.srv.full.virtual.entities.auth.Role;
import br.srv.full.virtual.entities.auth.User;
import br.srv.full.virtual.entities.persons.Worker;
import br.srv.full.virtual.entities.resume.UserLogin;
import br.srv.full.virtual.entities.resume.WorkerInClient;
import br.srv.full.virtual.faces.manager.menu.MenuManager;

/**
 * @author Delfino
 * 
 */
@TransactionManagement(TransactionManagementType.CONTAINER)
public final class UserRecordsManager {

	/**
	 * @author Delfino
	 * 
	 */
	public enum ActionLoginManager implements Action {
		/**
		 * 
		 */
		saveUserFailure,

		/**
		 * 
		 */
		saveUserSucess,

		/**
		 * 
		 */
		saveClientFailure
	}

	/**
	 * 
	 */
	private static final SelectItem SELECT_ITEM_NAO = new SelectItem(false, "Não");

	/**
	 * 
	 */
	private static final SelectItem SELECT_ITEM_SIM = new SelectItem(true, "Sim");

	private final Log log = LogFactory.getLog(getClass());

	/**
	 * 
	 */
	private LoginManager loginManager;

	private MenuManager menuManager;

	private PersonsManager personManager;

	/**
	 * 
	 */
	private User user;

	private Selection selectedWork;

	private WorkerInClient atualWork;

	private List<WorkerInClient> works;

	private Selection selectedClient;

	/**
	 * 
	 */
	private WorkSelectionManager workSelectionManager;

	/**
	 * @return the menuManager
	 */
	public MenuManager getMenuManager() {
		return menuManager;
	}

	/**
	 * @param p_menuManager
	 *            the menuManager to set
	 */
	public void setMenuManager(MenuManager p_menuManager) {
		menuManager = p_menuManager;
	}

	/**
	 * @return the loginManager
	 */
	public LoginManager getLoginManager() {
		return loginManager;
	}

	/**
	 * @param p_loginManager
	 *            the loginManager to set
	 */
	public void setLoginManager(LoginManager p_loginManager) {
		loginManager = p_loginManager;
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		if (user == null)
			updateUser();
		return user;
	}

	/**
	 * 
	 */
	private void updateUser() {
		try {
			UserLogin l_login = getLoginManager().getUserLogin();
			user = l_login.getUser();
			if (user == null) {
				l_login = getPersonManager().refreshUserLogin(l_login);
				getLoginManager().setUserLogin(l_login);
				getPersonManager().refresh(user, "works");
				user = l_login.getUser();

			}
		} catch (Exception e) {
			log.warn("Problemas ao Atualizar o User: " + user, e);
		}
	}

	/**
	 * @param p_user
	 *            the user to set
	 */
	public void setUser(User p_user) {
		user = p_user;
	}

	/**
	 * Salva os dados basicos do Usuário, e retorna qual página dever seguir.
	 * 
	 * @return
	 */
	public Action saveBaseUserRecord() {
		try {
			user = getPersonManager().update(user);
		} catch (PersonsManagerException e) {
			log.warn("Problemas ao salvar o usuário!", e);
			return ActionLoginManager.saveUserFailure;
		}
		getLoginManager().setUser(user);
		return ActionLoginManager.saveUserSucess;
	}

	/**
	 * Restora os dados Basicos do Usuário antes de ter salvo,
	 * 
	 * @return
	 */
	public String restoreBaseUserRecord() {
		return null;
	}

	/**
	 * Se o usuário é responsavel ou atua em alguma empresa, contem o numero de
	 * empresas.
	 * 
	 * @return
	 * 
	 * @see #getWorks()
	 */
	public Integer getNumClientsForUser() {
		Integer numClientsForUser = 0;
		try {
			List<WorkerInClient> l_works = getWorks();
			if (l_works != null)
				numClientsForUser = l_works.size();

		} catch (UserRecordsManagerException e) {
			log.warn("problemas ao obter o numero de clientes!", e);
		}
		log.info("Obtendo numero de Clientes: " + numClientsForUser);
		return numClientsForUser;
	}

	/**
	 * Retorna se atua em alguma empresa de alguma forma
	 * 
	 * é usado na página recordsmaintenance.xhtml.
	 * 
	 * @return
	 * @see #getNumClientsForUser()
	 */
	public Boolean isWorkerAtClients() {
		Boolean workerAtClients = getNumClientsForUser() > 0;
		log.info("Obtendo se trabalha em Clientes: " + workerAtClients);
		return workerAtClients;
	}

	public Boolean getWorkerAtClients() {
		return isWorkerAtClients();
	}

	/**
	 * Retorna as empresas onde o usuário logado atua!
	 * 
	 * @return
	 * @throws UserRecordsManagerException
	 */
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<WorkerInClient> getWorks() throws UserRecordsManagerException {
		try {
			User l_user = getUser();
			l_user = getPersonManager().refresh(l_user, User.FIELD_WORKS);

			if (l_user == null)
				throw new UserRecordsManagerException("Problemas ao obter o relacionamento do Usu'ario com o Cliente!");

			List<Worker> l_works = l_user.getWorks();
			if (works == null || l_works.size() != works.size() || !works.equals(l_works)) {
				List<WorkerInClient> l_result = new ArrayList<WorkerInClient>();

				setUser(l_user);
				l_works = l_user.getWorks();
				try {
					log.info("Atuando atualmente em: " + l_works.size());
					for (Worker l_work : l_works) {
						l_result.add(new WorkerInClient(l_work));
					}
				} catch (Exception e) {
					log.warn(" Problemas ao fazer um refresh do usuário!");
				}
				works = l_result;
			}
		} catch (PersonsManagerException e) {
			throw new UserRecordsManagerException(e);
		}
		return works;
	}

	public void setSelectedWork(Selection p_selection) {
		log.info(p_selection);
		selectedWork = p_selection;
	}

	/**
	 * @return the selectedWork
	 */
	public Selection getSelectedWork() {
		return selectedWork;
	}

	public void setSelectedClient(Selection p_selection) {
		log.info(p_selection);
		selectedClient = p_selection;
	}

	public void takeWorkSelected() {
		log.info("Take Client Selected!");
	}

	public WorkerInClient getAtualWork() {
		return atualWork;
	}

	public void setAtualWork(WorkerInClient p_client) {
		log.info(" Cadastrando o Trabalho Atual: " + p_client);
		atualWork = p_client;
	}

	public List<SelectItem> getSelectItensYesNo() {
		List<SelectItem> l_itens = new ArrayList<SelectItem>();

		l_itens.add(SELECT_ITEM_NAO);
		l_itens.add(SELECT_ITEM_SIM);

		return l_itens;
	}

	/**
	 * remove a empresa selecionada do usuário
	 */
	public String removeSelectedWorkForUser() {
		Selection l_selectedWork = getSelectedWork();
		Iterator l_works = l_selectedWork.getKeys();
		while (l_works.hasNext()) {
			Object l_obj = l_works.next();
			log.info(l_obj);

			// log.info("Removendo um trabalho " + l_selectedWork + " para o
			// usuário: " + getUser());
			Integer l_count = getNumClientsForUser();
			l_count = (l_count != null) ? --l_count : 0;

		}

		setAtualWork(null);

		return null;
	}

	/**
	 * Acionado quando se seleciona se o usu'ario atua ou n'ao em um cliente.
	 * 
	 * @param p_item
	 * @throws UserRecordsManagerException
	 */
	public void selectedWorkerAtClients(ValueChangeEvent p_item) throws UserRecordsManagerException {

		log.info("alterando e adicionando um novo Cliente se necessário!");
		Boolean l_workAtclients = getWorkerAtClients();
		if (!l_workAtclients)
			addMoreWorkForUser();

	}

	/**
	 * Remove a empresa selecionada do usuário.
	 * 
	 * @throws UserRecordsManagerException
	 * 
	 */
	public String addMoreWorkForUser() throws UserRecordsManagerException {
		log.info("Adicionando um novo cliente para o usuário: " + getUser());
		addWorkForUser(new WorkerInClient(getUser()));

		return null;
	}

	/**
	 * @param p_work
	 * @throws UserRecordsManagerException
	 */
	private void addWorkForUser(WorkerInClient p_work) throws UserRecordsManagerException {
		log.info("Adicionando um trabalho  " + p_work + " para o usuário: " + getUser());
		Integer l_count = getNumClientsForUser();
		l_count = (l_count != null) ? ++l_count : 1;

		getWorks().add(p_work);

		setAtualWork(p_work);

		takeWorkSelected();
	}

	public String cancelEditAtualWork() {
		return null;
	}

	@TransactionAttribute(TransactionAttributeType.MANDATORY)
	public Action saveEditAtualWork() {
		log.info("Salvando o Atual work");
		WorkerInClient l_atual = getAtualWork();

		try {
			getPersonManager().saveWork(l_atual);
		} catch (Exception e) {
			log.warn("Problemas ao salvar o atual trabalho para o usuário: " + l_atual.getUser(), e);
		}

		return null;
	}

	public List<SelectItem> getRoleTypesForUserWorkOnClient() {
		List<Role> l_roles = getPersonManager().getWorkerRoles();
		List<SelectItem> l_itens = new ArrayList<SelectItem>();
		for (Role l_workerRole : l_roles) {
			l_itens.add(new SelectItem(l_workerRole, l_workerRole.getName()));
		}
		return l_itens;
	}

	/**
	 * @return
	 */
	private PersonsManager getPersonManager() {
		if (personManager == null) {
			personManager = ServiceLocator.getService(PersonsManager.class);
		}

		return personManager;
	}

	/**
	 * @return the selectedClient
	 */
	public Selection getSelectedClient() {
		return selectedClient;
	}

	/**
	 * @return the workSelectionManager
	 */
	public WorkSelectionManager getWorkSelectionManager() {
		return workSelectionManager;
	}

	/**
	 * @param p_workSelectionManager
	 *            the workSelectionManager to set
	 */
	public void setWorkSelectionManager(WorkSelectionManager p_workSelectionManager) {
		workSelectionManager = p_workSelectionManager;
	}
}
>>>>>>> .r15
